package com.cby.android.olive.recyclerview

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

/**
 * @description: ViewBindingRecyclerAdapter
 * @author: ChenBaoYang
 * @createDate: 2022/6/27 11:32 上午
 */
abstract class ViewBindingRecyclerAdapter<VB : ViewBinding, T>(protected val context: Context,
                                                      protected val data: MutableList<T>? = null)
    : RecyclerView.Adapter<ViewBindingViewHolder<VB>>() {

    val inflater by lazy { LayoutInflater.from(context) }

    var mData: MutableList<T> = data ?: mutableListOf()

    abstract fun onBindData(holder: ViewBindingViewHolder<VB>, item: T?, position: Int)

    abstract fun onCreateViewBinding(layoutInflater: LayoutInflater, parent: ViewGroup, viewType: Int): VB


    override fun getItemCount(): Int {
        return mData.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)=  run {
        val viewBinding = onCreateViewBinding(inflater, parent, viewType)
        ViewBindingViewHolder(viewBinding)
    }

    override fun onBindViewHolder(holder: ViewBindingViewHolder<VB>, position: Int) {
        onBindData(holder, mData[position], position)
    }

    fun setItems(data: List<T>?) {
        if (data != null) {
            mData.clear()
            mData.addAll(data)
            notifyDataSetChanged()
        }
    }

    fun getAllData(): List<T> {
        return mData
    }
}